package scripts

class Utils {
	static createPathElementsForLibs(Ant, libs, prefix) {
		libs?.each {
			lib ->
			
			def libpath
			if (lib.toLowerCase().endsWith(".jar")) {
				libpath = "${prefix}/${lib}"
			} else {
				libpath = "${prefix}/${lib}.jar"
			}
			
			def libFile = new File(libpath)
			if (!libFile.exists() || !libFile.file) {
				throw new IllegalArgumentException("[ERROR] ${libpath} could not be found!")
			}
			Ant.pathelement( location: libpath )		
		}
	}

	static getProjectProperties(projectLocation) {
		def build_groovy = new File("${projectLocation}/Build.groovy")
		if (build_groovy.exists() && build_groovy.file) {
			def binding = new Binding()
			def shell = new GroovyShell(getClass().getClassLoader(), binding)
			shell.evaluate(build_groovy)
			
			return binding.variables
		} else {
			return [:]
		}
	}
	
	static getNestedProjectProperties(projectLocation) {			
		def projectProperties = getProjectProperties(projectLocation)

		if (projectProperties.deps) {
			def resolvedDeps = [:]
			projectProperties.deps.each {
				dependency ->
				
				def dependency_dir = new File("${new File( projectLocation ).parent}/${dependency}")
				
				if (!dependency_dir.exists() || !dependency_dir.directory) {
					throw IllegalArgumentException("[ERROR] Dependency [${dependency}] defined in ${build_groovy.absolutePath} could not be found")
				}
				
				resolvedDeps."${dependency}" = getNestedProjectProperties( dependency_dir.absolutePath )
			}
			
			projectProperties.deps = resolvedDeps
		}
		
		return projectProperties
	}

	static traverseProjectProperties(addLibs, project, properties) {
		
		addLibs(project, properties)
		
		properties.deps?.each {
			entry ->
			
			def dependency = entry.key
			def dependencyProjectProperties = entry.value
			
			traverseProjectProperties(addLibs, dependency, dependencyProjectProperties)
		}
	}


}